#include "logowidget.h"
#include "settings.h"

#include <QFileInfo>
#include <QFile>
#include <QSvgRenderer>
#include <QPainter>

LogoWidget::LogoWidget(QWidget *parent)
    : AGroupBox{parent}
{
    setFixedHeight(108);
    logo = new ALabel("LOGO", this);
    auto layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    logo->setStyleSheet(QString(R"(
        ALabel {
            color: #FFFFFF;
            background: transparent;
            font-size: %1px;
        }
    )").arg(30 * ratio()));
    logo->setAlignment(Qt::AlignCenter);

    layout->addWidget(logo);

    QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
    updateLoge(settings.value(LOGO_PATH).toString());
}

void LogoWidget::setLogo(const QString &fileName)
{
    if (!updateLoge(fileName)) {
        return ;
    }
    QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
    settings.setValue(LOGO_PATH, fileName);
}

bool LogoWidget::updateLoge(const QString &fileName)
{
    QFileInfo fileInfo(fileName);
    if (!fileInfo.exists()) {
        return false;
    }

    QString suffix = fileInfo.suffix().toLower();
    QPixmap pixmap;

    QSize targetSize(180 * ratio(), 100 * ratio());

    if (suffix == "svg") {
        QSvgRenderer renderer(fileName);
        if (!renderer.isValid()) { // 检查SVG是否有效
            return false;
        }

        pixmap = QPixmap(targetSize);
        if (pixmap.isNull()) { // 检查QPixmap是否有效
            return false;
        }
        pixmap.fill(Qt::transparent);

        QPainter painter(&pixmap);
        if (!painter.isActive()) { // 检查画家是否激活
            return false;
        }

        renderer.render(&painter, QRectF(pixmap.rect()));
    } else {
        if (!pixmap.load(fileName)) {
            return false;
        }
    }

    if (pixmap.isNull()) {
        return false;
    }

    QPixmap scaledPix = pixmap.scaled(
        targetSize,
        Qt::KeepAspectRatio,
        Qt::SmoothTransformation
        );
    logo->setPixmap(scaledPix);

    return true;
}
